package com.aaa.service.impl;

import com.aaa.mapper.SubscriptionFansMapper;
import com.aaa.netty.NettyConfig;
import com.aaa.service.NettypushServer;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.lang.model.element.VariableElement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class NettyPushServerImpl implements NettypushServer {
    @Autowired
    SubscriptionFansMapper subscriptionFansMapper;

    @Override
    public void pushidServer(String id, String msg) {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        Channel channel = userChannelMap.get(id);
        if(channel!=null) {
          channel.writeAndFlush(new TextWebSocketFrame(msg));
      }
    }

    @Override
    public void pushAllServer(String msg) {
        ChannelGroup channelGroup = NettyConfig.getChannelGroup();
        channelGroup.writeAndFlush(new TextWebSocketFrame(msg));
    }


    @Override
    public void push(Integer id, String msg) {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        List<Map<String, Object>> lssue = subscriptionFansMapper.lssue(id);
        for (Map map:lssue){
            Integer uid = (Integer) map.get("uid");
            Channel channel = userChannelMap.get(uid.toString());
            if(channel!=null){
                channel.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }
}
